//
//  HJPayBillController.m
//  KaiChat
//
//  Created by lx on 2023/12/22.
//

#import "HJPayBillController.h"
#import "HJPayBillCell.h"
#import "HJIM.h"
#import "HJChatMessageModel.h"
#import "HJWebViewController.h"
#import "TJEmptyDataHandler.h"

@interface HJPayBillController ()

@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, assign) NSInteger pageNumber;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) BOOL isLoadAllMessage;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
@property (nonatomic, strong) NSString *sessionId;
@property (nonatomic, strong) NSDictionary *iconDict;
@property (nonatomic, strong) TJEmptyDataHandler *emptyDataHandler;



@end

@implementation HJPayBillController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pageNumber = 1;
    self.pageSize = 20;
    
    self.navigationBar.title = @"Kai Pay";
    [self.view addSubview:self.tableView];
    self.view.backgroundColor = UIColor.tj_F6F6F6Color;
    self.tableView.backgroundColor = UIColor.tj_F6F6F6Color;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, TabbarSafeBottomMargin + 20, 0);
    [self.tableView registerClass:HJPayBillCell.class forCellReuseIdentifier:@"HJPayBillCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight);
        make.left.right.bottom.offset(0);
    }];

    _emptyDataHandler =  [TJEmptyDataHandler emptyDataHandleWithScrollView:self.tableView];
    self.sessionId = getOfficiaSessionId(@(KaiPaySessionId));
    [self loadData];
    [HJIM.shareIM.conversationManager readOfficialMessageWithSessionId:self.sessionId];
}


- (void)handleReceiveNewMessageNotification:(NSNotification *)not {
    dispatch_async_main_queue(^{
        HJChatMessageModel *messageModel = not.object;
        if (![self.navigationController.viewControllers containsObject:self]) return;
        if ([messageModel.sessionId isEqualToString:self.sessionId]) {
 
            HJPayBillModel *model = [HJPayBillModel modelWithMessageModel:messageModel];
            if (!model) {
                return;
            }

            [self.datas addObject:model];
            
            NSInteger totalRow = [self.tableView numberOfRowsInSection:0];
            [UIView setAnimationsEnabled:NO];
            [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:totalRow inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            [UIView setAnimationsEnabled:YES];
            
            dispatch_async_main_queue(^{
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(100 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
                    [self scrollToBottom:YES];
                });
            });
        }
    });
}
 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJPayBillCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJPayBillCell" forIndexPath:indexPath];
    cell.model = self.datas[indexPath.row];;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HJPayBillModel *model = self.datas[indexPath.row];
    NSLog(@"model = %@", model);

    if (isEmptyString(model.url)) {
        return;
    }
    
    if (model.clickEvent == 102) {
        NSDictionary *msgDict = [model.msg mj_JSONObject];
        HJWebViewController *webViewController = [[HJWebViewController alloc] init];
        webViewController.type = HJWebViewTypePay;
        webViewController.content = [msgDict[@"content"] mj_JSONString];
        webViewController.url = model.url;
        [self presentViewController:webViewController animated:YES completion:nil];
        return;
    }
    
    if (model.clickEvent == 200) {
        [[UIApplication sharedApplication] openURL:model.url.URL options:@{} completionHandler:nil];
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJPayBillModel *model = self.datas[indexPath.row];
    return model.height;
}

- (void)loadData {
    
    self.pageNumber = 1;
    [HJIM.shareIM.messageManager loadMessageDatasBySessionId:self.sessionId pageSize:self.pageSize pageNumber:self.pageNumber completion:^(NSArray * _Nonnull messages) {
            
        self.pageNumber++;
        
        for (NSInteger i = messages.count - 1; i >= 0; i--) {
            HJChatMessageModel *messageModel = messages[i];
            
            HJPayBillModel *model = [HJPayBillModel modelWithMessageModel:messageModel];
            if (!model) {
                continue;
            }
            [self.datas addObject:model];
        }
        
        dispatch_async_main_queue(^{
            if (messages.count < self.pageSize) {
                self.isLoadAllMessage = YES;
            }
            self.emptyDataHandler.canDisplay = YES;
            [self.tableView reloadData];
            [self.tableView layoutIfNeeded];
            [self scrollToBottom:NO];
        });
    }];
}

- (void)loadMoreData {
    
    [HJIM.shareIM.messageManager loadMessageDatasBySessionId:self.sessionId pageSize:self.pageSize pageNumber:self.pageNumber completion:^(NSArray * _Nonnull messages) {
        
        self.pageNumber++;
        
        
        NSMutableArray *billModels = [NSMutableArray array];

        __block CGFloat visibleHeight = 0;

        for (NSInteger i = messages.count - 1; i >= 0; i--) {
            HJChatMessageModel *messageModel = messages[i];
            
            HJPayBillModel *model = [HJPayBillModel modelWithMessageModel:messageModel];
            if (!model) {
                continue;
            }
            visibleHeight += model.height;
            [billModels addObject:model];
        }
 
        dispatch_async_main_queue(^{
            
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, billModels.count)];
            [self.datas insertObjects:billModels atIndexes:indexSet];
            
            [self.tableView layoutIfNeeded];
            [self.tableView reloadData];
            
            if (messages.count < self.pageSize) {
                self.isLoadAllMessage = YES;
            }
            
            if (self.isLoadAllMessage) {
                [self.indicatorView stopAnimating];
            }
            
            [self.tableView scrollRectToVisible:CGRectMake(0, self.tableView.contentOffset.y + visibleHeight - self.tableView.contentInset.bottom - 10, self.tableView.frame.size.width, self.tableView.frame.size.height) animated:NO];
        });
    }];
}

- (void)scrollToBottom:(BOOL)animated {
    NSInteger totalRow = [self.tableView numberOfRowsInSection:0];
    if (totalRow == 0 || self.datas.count == 0) return;
    if (totalRow == self.datas.count) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.datas.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:animated];
    } else {
        [self.tableView reloadData];
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.datas.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:animated];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y <= 1
        && !_isLoadAllMessage) {
        [self loadMoreData];
    }
}

- (NSMutableArray *)datas {
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

 

